#include "datapack.h"

#define LEN_ADECIMAL 128  // 长度字段的进制


DataPack::DataPack(QObject *parent) : QObject(parent)
{

}

void DataPack::parsingOk(uint8_t t,uint16_t l,QList<uint8_t> p,uint8_t ckh,uint8_t ckl){
    package.payload.clear();
    package.type = t;
    package.len = l;
    package.payload = p;
    package.ckH =ckh;
    package.ckL = ckl;

    if(package.type==MSG_FIRMWARE_REQ){  // 当前固件包数
        qDebug() << package.len<<" "<<package.payload[0]<<" "<<package.payload[1];
        if(package.len==1){
            packetIndex = package.payload[0];
        }
         else if (package.len==2) {
            packetIndex = (((uint16_t)package.payload[0])<<8)+package.payload[1];
        }
    }
}



void DataPack::checkSum(void)
{
    uint16_t sum=0;
    sum +=package.type;
    if(package.len<=127){
        sum += package.len;
    }
    else  {
        sum += ((package.len/LEN_ADECIMAL) | 0x80);
        sum += (package.len%LEN_ADECIMAL);
    }
    for (int i=0;i<package.payload.size();i++) {
        sum+=package.payload[i];
    }
    package.ckH = sum>>8;
    package.ckL = sum;

}

void DataPack::setDataPack(uint8_t t,uint16_t l,QList<uint8_t> p)
{
    package.type = t;
    package.len = l;
    package.payload = p;
    checkSum();
}

uint8_t *DataPack::getArrayData()
{
    uint8_t *buff,lenSize=1;

    if(package.len>=LEN_ADECIMAL)  lenSize = 2;
    dataLen = package.payload.size()+lenSize+4;  // len字段长度可变，4（head+type+ckH+ckL）
    buff = (uint8_t *)malloc(dataLen);
    buff[0] = package.head;
    buff[1] = package.type;
    if(lenSize==1){
        buff[2] = package.len;
    }
    else if(lenSize==2) {
        buff[2] = (package.len/LEN_ADECIMAL) | 0x80;
        buff[3] = package.len%LEN_ADECIMAL;
    }

    for (int i=0;i<package.payload.size();i++) {
        buff[2+i+lenSize]=package.payload[i];
    }
    buff[dataLen-2] = package.ckH;
    buff[dataLen-1] = package.ckL;
    return buff;
}

int DataPack::getArrayDataLen(){
    return dataLen;
}
